import { useState, useCallback, useMemo, useEffect } from "react";
import { type HistoryRecord } from "./type";
export function useHistoryRecords<T extends HistoryRecord>(initialState?: T[]) {
  const [history, setHistory] = useState<T[]>(initialState || []);
  const [currentIndex, setCurrentIndex] = useState(-1);

  // 添加新的历史记录
  const push = useCallback(
    (state: T) => {
      const newHistory = history.slice(0, currentIndex + 1);
      newHistory.push(state);
      setHistory(newHistory);
      setCurrentIndex(newHistory.length - 1);
    },
    [history, currentIndex]
  );

  // 撤销
  const undo = useCallback(() => {
    if (currentIndex >= 0) {
      setCurrentIndex(currentIndex - 1);
      return history[currentIndex - 1];
    }
    return history[currentIndex];
  }, [history, currentIndex]);

  // 重做
  const redo = useCallback(() => {
    if (currentIndex < history.length - 1) {
      setCurrentIndex(currentIndex + 1);
      return history[currentIndex + 1];
    }
    return history[currentIndex];
  }, [history, currentIndex]);

  // 是否可以撤销
  const canUndo = currentIndex >= 0;

  // 是否可以重做
  const canRedo = currentIndex < history.length - 1;

  // 获取当前生效的历史记录列表
  const validRecords = useMemo(() => {
    return history.slice(0, currentIndex + 1);
  }, [history, currentIndex]);

  // 监听快捷键
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.ctrlKey && e.key === "z") {
        e.preventDefault();
        undo();
      } else if (e.ctrlKey && e.key === "y") {
        e.preventDefault();
        redo();
      }
    },
    [undo, redo]
  );

  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [handleKeyDown]);

  const clear = useCallback(() => {
    setHistory([]);
    setCurrentIndex(-1);
  }, []);

  return useMemo(()=>{
    return {
      state: history[currentIndex],
      records: validRecords,
      push,
      undo,
      redo,
      canUndo,
      canRedo,
      clear,
    }
  }, [canRedo, canUndo, clear, currentIndex, history, push, redo, undo, validRecords]);
}
